package com.tywj.module.h5.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient

/**
 * 自定义 X5WebView
 */
class X5WebView constructor(context: Context?, attributeSet: AttributeSet?) :
    WebView(context, attributeSet) {
    var title: TextView? = null
    private val client: WebViewClient = object : WebViewClient() {
        /**
         * 防止加载网页时调起系统浏览器
         */
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }
    }

    init {
        this.webViewClient = client
        this.view.isClickable = true
        initWebViewSettings()
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebViewSettings() {
        val webSetting = this.settings

        webSetting?.run {
            ////如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
            javaScriptEnabled = true
            javaScriptCanOpenWindowsAutomatically = true
            allowFileAccess = true

            setSupportZoom(true)
            builtInZoomControls = true
            useWideViewPort = true

            setSupportMultipleWindows(true)
            setAppCacheEnabled(true)
            domStorageEnabled = true
            setGeolocationEnabled(true)
            setAppCacheMaxSize(Long.MAX_VALUE)

            this.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS

            this.pluginState = WebSettings.PluginState.ON_DEMAND
            // 不使用缓存，只从网络获取数据
            this.cacheMode = WebSettings.LOAD_NO_CACHE
        }
    }
}
